﻿using System;
using System.Linq;
using System.Windows.Controls;
using System.Collections.Generic;
using System.Windows.Media;
using System.Windows;

namespace Windows.Toolbar.Controls.Specialized
{
    public partial class ColorPicker : SelectionContainer
    {
        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ColorPicker"/> class.
        /// </summary>
        public ColorPicker()
        {
            InitializeComponent();
        }

        #endregion

        #region Methods

        protected override void OnSelectedValueChanged()
        {
            List<ColorPickerItem> items = GetItems();

            if (SelectedValue == null)
            {
                foreach (ColorPickerItem item in items)
                {
                    if (item != null)
                    {
                        item.IsSelected = false;
                    }
                }
            }
            else
            {
                var selectedItem = items.Where(x => x.Color == (Color)SelectedValue).FirstOrDefault();

                if (selectedItem != null)
                {
                    selectedItem.IsSelected = true;
                }
            }

            base.OnSelectedValueChanged();
        }

        private void ColorPickerItem_Selected(object sender, EventArgs e)
        {
            ColorPickerItem colorPickerItem = sender as ColorPickerItem;

            if (colorPickerItem != null && colorPickerItem.IsSelected)
            {
                List<ColorPickerItem> items = GetItems();

                foreach (ColorPickerItem item in items)
                {
                    if (item != null && item != colorPickerItem)
                    {
                        item.IsSelected = false;
                    }
                }

                SelectedValue = colorPickerItem.Color;
            }
        }

        private List<ColorPickerItem> GetItems()
        {
            List<ColorPickerItem> items = new List<ColorPickerItem>();

            GetItems(items, this);

            return items;
        }

        private void GetItems(List<ColorPickerItem> items, DependencyObject reference)
        {
            int numChildren = VisualTreeHelper.GetChildrenCount(reference);
            for (int i = 0; i < numChildren; i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(reference, i);

                ColorPickerItem colorItem = child as ColorPickerItem;
                if (colorItem != null)
                {
                    items.Add(colorItem);
                }
                else
                {
                    GetItems(items, child);
                }
            }
        }

        #endregion
    }
}
